import React, {PureComponent} from "react";
import {Icon, Popconfirm, Table} from "antd";
import {connect} from "react-redux";
import {paginationProps, tableProps} from "../../lib/ui";
import {
    del,
    findFeesByClientId,
    getById,
    getFeeList,
    getVehicleFeesByClientId,
    query,
    queryLinePrice,
    showModify,
    updateBaoGuanFee
} from "./actions";
import {query as coachQuery} from "../coach/actions";
import {query as lineQuery} from "../line/actions";
import {getCurrentOrganization, getLastFilter, getPrincipal} from "../../lib/identity";
import {organizations} from "../home/actions";
import {getCurrencyList} from "../zadOrder/actions";
import {query as vehicleQuery} from "../vehicle/actions";
import {Resizable} from "react-resizable";
import moment from "moment";
import {DATE_FORMAT} from "../../lib/func";

const LAST_FILTER = "client";

const ResizeableTitle = props => {
    const {onResize, width, ...restProps} = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{enableUserSelectHack: false}}
        >
            <th {...restProps} />
        </Resizable>
    );
};

class List extends PureComponent {

    state = {
        columns: [
            {
                title: "客户编号",
                dataIndex: "code",
                width: 150,
                render: (text, record) => (
                    <a
                        onClick={() => {
                            this.handleModify(record.id);
                        }}
                    >
                        {text}
                    </a>
                )
            }, {
                title: "客户简称",
                dataIndex: "name",
                width: 150,
                ellipsis: true
            }, {
                title: "客户全称",
                dataIndex: "fullName",
                width: 150,
                ellipsis: true
            }, {
                title: "营业执照",
                dataIndex: "licence",
                width: 150
            }, {
                title: "结算周期(天)",
                dataIndex: "settlementDays",
                width: 100
            }, {
                title: "合同名称",
                dataIndex: "contractName",
                width: 180
            }, {
                title: "合同编号",
                dataIndex: "contractNumber",
                width: 180
            }, {
                title: "签订日期",
                dataIndex: "signedDate",
                width: 180,
            }, {
                title: "结束日期",
                dataIndex: "expiresDate",
                width: 180
            }, {
                title: "到期提醒",
                dataIndex: "remindDate",
                width: 180
            }, {
                title: "所属抬头",
                dataIndex: "taiTou",
                width: 180
            }
        ]
    };

    onPageChange = (page, pageSize) => {
        const {dispatch, filter} = this.props;
        dispatch(query({...filter, "currentOrgId": getCurrentOrganization(), page, pageSize}));
    };


    handleModify = id => {
        const {dispatch, dataSource} = this.props;
        dispatch(getById(id));
        const found = dataSource.find(item => item.id === id);
        if (found) {
            dispatch(updateBaoGuanFee({
                homeFee: found.homeFee,
                sheetFee: found.sheetFee,
                currency: found.currency,
                sheetCurrency: found.sheetCurrency
            }));
        }
        dispatch(getFeeList()).then(() => {
            dispatch(findFeesByClientId(id));
            dispatch(queryLinePrice({"belongId": id}));
            dispatch(showModify());
            dispatch(getVehicleFeesByClientId({"ownerId": id}));
        });
    };


    handleDeleteClient = id => {
        const {dispatch, filter} = this.props;
        dispatch(del(id)).then(() => {
            dispatch(query({...filter, "userId": getPrincipal().id, "currentOrgId": getCurrentOrganization()}));
        });
    };

    componentWillMount() {
        const {dispatch, page, pageSize} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({
            "userId": getPrincipal().id,
            "currentOrgId": getCurrentOrganization(), ...fields,
            page,
            pageSize
        }));
        dispatch(getCurrencyList());
        dispatch(coachQuery());
        dispatch(lineQuery({}));
        dispatch(organizations(getPrincipal().id));
        dispatch(vehicleQuery({}));
    };

    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    components = {
        header: {
            cell: ResizeableTitle,
        },
    };

    render() {
        const columns = this.state.columns;
        if (getPrincipal().admin) {
            const found = columns.find(item => item.title === '功能');
            if (!found) {
                columns.push(
                    {
                        title: '功能',
                        dataIndex: '',
                        key: 'x',
                        width: 50,
                        align: 'center',
                        fixed: 'right',
                        render: (text, record) => <span>
                    <Popconfirm title="确定删除此客户?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDeleteClient(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>,
                    }
                );
            }
        }
        const {
            page,
            pageSize,
            totalElements,
            dataSource,
            loading
        } = this.props;

        const resizeColumns = columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));

        const tablePagination = {
            ...paginationProps,
            total: totalElements,
            current: page,
            pageSize: pageSize,
            onShowSizeChange: (current, newSize) =>
                this.onPageChange && this.onPageChange(1, newSize),
            onChange: this.onPageChange
        };

        return (
            <Table
                {...tableProps}
                columns={resizeColumns}
                components={this.components}
                scroll={{x: 1500}}
                pagination={tablePagination}
                dataSource={dataSource}
                loading={loading}
            />
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.client.list
    };
};

export default connect(mapStateToProps)(List);
